package com.keter.config;

import com.keter.domains.MyClientUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.NoSuchClientException;

/**
 * Created by gulx@neusoft.com on 2020/6/1.
 */
public class MyUserDetailService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailService.class);

    /**
     * 必须Client验证通过后调用User验证方法
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("********* invoke MyClientUserDetailService ********");
        MyClientUserDetails clientDetails;
            try {
                clientDetails = ClientUserUtil.instance().retrieveClientDetails(username);
            } catch (NoSuchClientException e) {
                throw new UsernameNotFoundException(e.getMessage(), e);
            }
            String clientSecret = clientDetails.getClientSecret();
            if (clientSecret== null || clientSecret.trim().length()==0) {
                clientSecret = "";
            }
            return new User(username, clientSecret, clientDetails.getAuthorities());
        }
}
